import {buildUrl} from "../net";
import template from "./tpl";
import {hideLoading, 
        showLoading, 
        showToast, 
        getSystemInfoSync, 
        getSetting} from "./wx";

export class BaseCom {
    ele = {};
    __attachRefs(context) {
        let self = this;
        let sys = getSystemInfoSync();
        self.data = {
            $sys: sys
        };
        self.refs && self.refs.forEach((n)=> {
            self.ele[n] = context.selectComponent("#" + n);
        });
    }
    _buildUrl(url, query) {
        return buildUrl(url, query);
    }
    data = {};
    properties = {};
    exports = {};
    methods = {
        $buildUrl(url, query) {
            return buildUrl(url, query);
        },
        _setByKey: function (k, v) {
            return this.setData({
                [k]: v
            })
        },
        _getComponentById: function (id) {
            return this.selectComponent("#" + id);
        },
        $setByKey: function (k, v) {
            return this.setData({
                [k]: v
            })
        },
        $getComponentById: function (id) {
            return this.selectComponent("#" + id);
        },
        $setDataTrueIfOldIsFase(k) {
            let self = this;
            if (!self.data[k]) {
                self.setData({
                    [k]: true
                })
            }
        },
        $toast(title = '', opt = {}) {
            showToast({
                title: title,
                ...opt
            })
        },
        $toggleLoading(show) {
            if (show) {
                showLoading();
            } else {
                hideLoading();
            }
        },
        $getSettingByKey(key) {
            return new Promise((resolve, reject) => {
                getSetting().then(function (res) {
                    if (res.authSetting && res.authSetting.hasOwnProperty(key)) {
                        resolve(res.authSetting[key]);
                    } else {
                        resolve(null);
                    }
                }).catch(function (e) {
                    reject(e);
                })
            })
        },
        $getShareAppMessage(title, path, opt = {imageUrl: ''}) {
            return {
                title: title,
                path: path,
                ...opt
            }
        },
        $template(...args) {
            return template(...args);
        }
    }
}